from langchain_zhipu import ChatZhipuAI,ZhipuAIEmbeddings
from langchain_core.output_parsers import StrOutputParser
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_core.prompts import ChatPromptTemplate

from langchain.chains.combine_documents import create_stuff_documents_chain

from langchain_core.documents import Document
from langchain_community.document_loaders import WebBaseLoader



llm = ChatZhipuAI(api_key="d3708ee404327e207b2f003775e06908.X3dgRCxbkyDfEIbh", model="glm-4")


loader = WebBaseLoader("https://docs.spring.io/spring-data/elasticsearch/docs/4.4.3/reference/html/#preface")

docs = loader.load()
embeddings = ZhipuAIEmbeddings(api_key="d3708ee404327e207b2f003775e06908.X3dgRCxbkyDfEIbh")
text_splitter = RecursiveCharacterTextSplitter()
documents = text_splitter.split_documents(docs)
print(documents)
vector = FAISS.from_documents(documents, embeddings)

prompt = ChatPromptTemplate.from_template("""Answer the following question based only on the provided context:

<context>
{context}
</context>

Question: {input}""")

document_chain = create_stuff_documents_chain(llm, prompt)




output_parser = StrOutputParser()




answer = document_chain.invoke({
    "input": "how can spring data elasticsearch help with testing?",
    "context": [Document(page_content="langsmith can let you visualize test results")]
})
print(answer)
